package org.weso.desempleo.model;

import org.weso.desempleo.services.to.ListSectoresStatsTO;
import org.weso.desempleo.to.SectorStatsTO;

import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;

public class ChargerSectors extends Charger<ListSectoresStatsTO, SectorStatsTO>{
	
	public ChargerSectors() {
		if(months[0][0] == null) {
			initializeMonths();
		}
	}

	@Override
	public String prepareSparqlQuery(String anyo, String selector, String month,
			String lang) {
		String query="PREFIX o: <http://purl.org/observatory/observatory.owl#>\n"+
				"SELECT ?year ?month ?sector ?value\n FROM " + 
				"<http://purl.org/weso/testObservatory/observatoryBySectors/> \n WHERE{ ?x <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> " +
				"<http://purl.org/linked-data/cube#Observation>; o:refYear ?year; o:refMonth ?month; o:unemployment ?value; o:refSector ?sector"; 
		query += parseYear(anyo);
		query += " FILTER (langMatches(lang(?month), '" + lang +"')" + parseMonth(month) +")\n";
		query += " FILTER (langMatches(lang(?sector), '" + lang +"')" + parseSector(selector) + ")";
		return query+"}";
	}
	
	/**
	 * This method parse the variable 'sector' to obtain a part of the SPARL 
	 * query.
	 * @param sector The value of sector that the user has selected in the form.
	 * @return A part of the SPARQL query.
	 */
	private String parseSector(String sector) {
		if(sector.equals("Todos") || sector.equals("All"))
			return "";
		return "&& str(?sector)=\"" + sector +"\"";
	}
	
	/**
	 * This method obtain the value of variable 'sector' when the user change
	 * the language of exhibit page.
	 * @param sector The value of sector that user select in the form.
	 * @param newLang The new language that user select.
	 * @param oldLang The old language
	 * @return The new value of variable 'sector'
	 */
	public String getNewSector(String sector, String newLang, String oldLang) {
		if(sector.equals("Todos") || sector.equals("All"))
			return sector;
		else {
			String query = "PREFIX o: <http://purl.org/observatory/observatory.owl#>\n" + 
					"SELECT DISTINCT ?oldSector ?newSector FROM <http://purl.org/weso/testObservatory/observatoryBySectors/>" + 
					"WHERE {?x <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>" +
					"<http://purl.org/linked-data/cube#Observation>; o:refSector ?oldSector;" + 
					"o:refSector ?newSector \n FILTER (langMatches(lang(?oldSector), \"" + oldLang + "\") && str(?oldSector) =\"" + sector + "\")" + 
					"FILTER (langMatches(lang(?newSector), \"" + newLang + "\"))}";
			QueryExecution qExec = initializeQuery("http://156.35.31.156/sparql", query);
			ResultSet result = qExec.execSelect();
			if(result.hasNext()) {
				QuerySolution solution = result.next();
				String sol = solution.get("newSector").toString();
				return sol.substring(0, sol.indexOf('@'));				
			}
			return sector;
		}
	}

	@Override
	public ListSectoresStatsTO obtain(String lang, String anyo, String month,
			String selector, String langAnt) {
		if(langAnt != null && !langAnt.equals("null") && !langAnt.equals(lang)) {
			selector = getNewSector(selector, lang, langAnt);
			month = getNewMonth(month, lang, langAnt);
		}
		String query = prepareSparqlQuery(anyo, selector, month, lang);
		QueryExecution qExec = initializeQuery("http://156.35.31.156/sparql", query);
		ListSectoresStatsTO sectors = (ListSectoresStatsTO)processResult(qExec.execSelect());
		return sectors;
	}

	@Override
	public SectorStatsTO extractData(QuerySolution sol, int observaciones) {
		String aux = sol.get("month").toString();
		String m = aux.substring(0, aux.indexOf('@'));
		String month = extractMonth(m);
		int year = Integer.parseInt(sol.get("year").toString());
		aux = sol.get("sector").toString();
		String sector = aux.substring(0, aux.indexOf('@'));
		String period = String.valueOf(year) + "-" + month;
		int unemployment = Integer.valueOf(sol.get("value").toString());
		String dataset = "Paro por sectores en el principado de Asturias" + 
		" desde el año 2005";
		String label = "o" + String.valueOf(observaciones);
		return new SectorStatsTO(sector, label, dataset, year, unemployment, 
				period, month);
	}

	@Override
	public ListSectoresStatsTO processResult(ResultSet result) {
		ListSectoresStatsTO sectores = new ListSectoresStatsTO();
		int observaciones = 1;
		while(result.hasNext()) {
			SectorStatsTO sector = (SectorStatsTO)extractData(result.next(), 
					observaciones);
			sectores.add(sector);
			observaciones++;
		}
		return sectores;
	}

}
